package edu.ynu.se.xiecheng.achitectureclass.project.controller;

import edu.ynu.se.xiecheng.achitectureclass.project.service.VideoTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/token")
public class VideoTokenController {

    @Autowired
    private VideoTokenService videoTokenService;

    /**
     * 获取视频 Token
     */
    @PostMapping("/video")
    public ResponseEntity<Map<String, Object>> getVideoToken(HttpServletResponse response) {
        try {
            // 设置响应头
            response.setHeader("X-Content-Type-Options", "nosniff"); // 防止MIME类型嗅探
            response.setHeader("Cache-Control", "public, max-age=3600"); // 设置缓存策略为可缓存1小时
            response.setHeader("Content-Type", "application/json; charset=utf-8"); // 显式设置Content-Type和字符集

            // 获取 Token 数据
            Map<String, Object> tokenData = videoTokenService.getVideoToken();

            // 返回响应
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)  // 使用 UTF-8 的 MediaType
                    .body(tokenData);
        } catch (Exception e) {
            // 构建标准的 Spring Boot 错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("timestamp", new Date());
            errorResponse.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorResponse.put("error", "Internal Server Error");
            errorResponse.put("path", "/api/token/video");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .contentType(MediaType.APPLICATION_JSON)  // 使用 UTF-8 的 MediaType
                    .body(errorResponse);
        }
    }
}